package qqopenapi_v3

import (
  "fmt"
  "log"
  "strings"
  "net/url"
  "crypto/hmac"
  "crypto/sha1"
  "encoding/base64"
)

func pay_mk_source(method, url_path string, params url.Values) string {
  return fmt.Sprintf("%s&%s&%s", 
            strings.ToUpper(method), 
            url.QueryEscape(url_path), 
            url_encode(params, true))
}

func pay_hmac_sha1_sig(method, url_path, secret string, params url.Values) string {
  var source = pay_mk_source(method, url_path, params)
  var hashed = hmac.New(sha1.New, []byte(secret))
  n, err := hashed.Write([]byte(source))
  if n != len(source) || err != nil {
    log.Println("Hmac write error!", err)
    return ""
  }
  return base64.StdEncoding.EncodeToString(hashed.Sum(nil))
}

func verify_pay_callback_sig(appkey, method, url_path string, params url.Values) bool {
  var input_sig = params.Get("sig")
  params.Del("sig")

  var sig = pay_hmac_sha1_sig(method, url_path, appkey + "&", params)
  return sig == input_sig
}